﻿using System;
using System.IO;
using System.Text;

namespace MultiThread.DosApp
{
	/// <summary>
	/// 菜园子
	/// </summary>
	public class Garden
	{
		/// <summary>
		/// 单例对象
		/// </summary>
		private static Garden _theInstance = null;

		/// <summary>
		/// 白菜当前数量
		/// </summary>
		private int _currCount = -1;

		/// <summary>
		/// 白菜最大数量
		/// </summary>
		private const int MAX_COUNT = 3;

		/// <summary>
		/// 配置文件路径
		/// </summary>
		private const String INI_PATH = "C:/temp+test/Garden.ini";

		#region 类构造器
		/// <summary>
		/// 类默认构造器
		/// </summary>
		private Garden()
		{
			// 进行自定义初始化
			this.CustomInit();
		}
		#endregion

		/// <summary>
		/// 获取菜园子对象
		/// </summary>
		public static Garden Instance
		{
			get
			{
//				lock (typeof(Garden))
//				{
					if (Garden._theInstance == null)
					{
						// 创建菜园子
						Garden._theInstance = new Garden();

						// 输出消息
//						Console.WriteLine("Created Garden");
					}
//				}

				return Garden._theInstance;
			}
		}

		/// <summary>
		/// 自定义初始化
		/// </summary>
		private void CustomInit()
		{
			// 创建配置文件
//			this.CreateINIFile();
			// 读取白菜数量
			this._currCount = this.LoadCabbageCountFromINI();
		}

		/// <summary>
		/// 创建配置文件
		/// </summary>
		private void CreateINIFile()
		{
			using (StreamWriter sw = new StreamWriter(Garden.INI_PATH, false, Encoding.UTF8))
			{
				sw.WriteLine(Garden.MAX_COUNT);
				sw.Flush();
				sw.Close();
			}
		}

		/// <summary>
		/// 从配置文件中获取白菜数量
		/// </summary>
		/// <returns></returns>
		private int LoadCabbageCountFromINI()
		{
			using (StreamReader sr = new StreamReader(Garden.INI_PATH, Encoding.UTF8))
			{
				String ln = sr.ReadLine();

				if (String.IsNullOrEmpty(ln))
				{
					return 0;
				}

				return Convert.ToInt32(ln);
			}
		}

		/// <summary>
		/// 保存白菜数量到配置文件中
		/// </summary>
		/// <param name="count"></param>
		private void SaveCabbageCountToINI(int count)
		{
			using (StreamWriter sw = new StreamWriter(Garden.INI_PATH, false, Encoding.UTF8))
			{
				sw.WriteLine(count);
				sw.Flush();
				sw.Close();
			}
		}

		/// <summary>
		/// 丢失白菜
		/// </summary>
		/// <returns></returns>
		public String Lose()
		{
//			lock (this)
//			{
				if (this._currCount > 0)
				{
					this._currCount--;

					// 保存白菜数量到配置文件
//					this.SaveCabbageCountToINI(this._currCount);

					return "Cabbage";
				}
				else
				{
					return null;
				}
//			}
		}
	}
}
